package cn.com.basic.framework.aliyun.oss.upload;


import cn.com.basic.framework.aliyun.oss.OSSManager;
import cn.hutool.core.lang.Assert;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.Callback;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 表单上传是使用HTML表单形式上传文件到指定存储空间中，文件最大不能超过5GB。
 * 适用场景
 * 表单上传非常适合嵌入在HTML网页中来上传Object，比较常见的场景是网站应用，以招聘网站为例：
 * <table>
 * <thead></thead><tr>
 * <th></th>
 * <th>不使用表单上传</th>
 * <th>表单上传</th>
 * </tr></thead>
 * <tbody>
 * <tr><td>流程对比</td>
 * <td><ol>
 * <li>网站用户上传简历。 </li>
 * <li>网站服务器回应上传页面。</li>
 * <li>简历被上传到网站服务器。 </li>
 * <li>网站服务器再将简历上传到OSS。</li>
 * </ol></td>
 * <td><ol>
 * <li>网站用户上传简历。 </li>
 * <li>网站服务器回应上传页面。</li>
 * <li>简历上传到OSS。</li>
 * </ol></td>
 * </tr></tbody>
 * </table>
 * 从流程上来说，使用表单上传，少了一步转发流程，更加方便。
 * 从架构上来说，原来的上传都统一走网站服务器，上传量过大时，需要扩容网站服务器。采用表单上传后，直接从客户端上传数据到OSS，上传量过大时，压力都在OSS上，由OSS来保障服务质量。
 *
 * @author zhuxj
 */
public class FormUploader extends Uploader {

    private static Logger logger = LoggerFactory.getLogger(FormUploader.class);

    public FormUploader(OSSManager ossManager) {
        super(ossManager);
    }

    /**
     * 表单方式上传文件
     *
     * @param localFilePath 文件路径
     * @param bucketName    目标存储空间
     * @param objectName    目标文件名称
     * @param callBackUrl   回调服务器地址，如http://oss-demo.aliyuncs.com:23450或http://127.0.0.1:9090。
     * @param callBackHost  回调请求消息头中Host的值，如oss-cn-hangzhou.aliyuncs.com
     * @throws Exception
     */
    public String uploadForm(String localFilePath, String bucketName, String objectName, String callBackUrl, String callBackHost) throws Exception {
        Assert.isTrue(this.ossManager.getOss() != null, "oss client cannot be null");

        String urlStr = this.ossManager.getEndpoint().replace("http://", "http://" + bucketName + ".");

        Map<String, String> formData = new LinkedHashMap<>();

        // 设置文件名称。
        formData.put("key", objectName);
        // 设置Content-Disposition。
        formData.put("Content-Disposition", "attachment;filename=" + localFilePath);

        // 设置回调参数。
        Callback callback = new Callback();
        // 设置回调服务器地址，如http://oss-demo.aliyuncs.com:23450或http://127.0.0.1:9090。
        callback.setCallbackUrl(callBackUrl);
        // 设置回调请求消息头中Host的值，如oss-cn-hangzhou.aliyuncs.com。
        callback.setCallbackHost(callBackHost);
        // 设置发起回调时请求body的值。
        callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
        // 设置发起回调请求的Content-Type。
        callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);

        String jsonCb = OSSUtils.jsonizeCallback(callback);
        String base64Cb = BinaryUtil.toBase64String(jsonCb.getBytes());
        formData.put("callback", base64Cb);
        if (callback.hasCallbackVar()) {
            Map<String, String> varMap = callback.getCallbackVar();
            for (Map.Entry<String, String> entry : varMap.entrySet()) {
                formData.put(entry.getKey(), entry.getValue());
            }
        }

        formData.put("OSSAccessKeyId", this.ossManager.getAccessKeyId());
        String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
        String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
        // 设置policy。
        formData.put("policy", encodePolicy);

        // 生成签名。
        String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(this.ossManager.getAccessKeySecret(), encodePolicy);
        // 设置签名。
        formData.put("Signature", signaturecom);
        String ret = formUpload(urlStr, formData, localFilePath);

        logger.info("Post Object [" + objectName + "] to bucket [" + bucketName + "]");
        logger.info("post reponse:" + ret);

        return ret;
    }

    private static String formUpload(String urlStr, Map<String, String> formFields, String localFile) throws Exception {
        String res = "";
        HttpURLConnection conn = null;
        String boundary = "9431149156168";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            // 设置MD5值。MD5值是由整个body计算得出的。
            conn.setRequestProperty("Content-MD5", "<yourContentMD5>");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // 遍历读取表单Map中的数据，将数据写入到输出流中。
            if (formFields != null) {
                StringBuilder strBuf = new StringBuilder();
                Iterator<Map.Entry<String, String>> iter = formFields.entrySet().iterator();
                int i = 0;
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = entry.getKey();
                    String inputValue = entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    if (i == 0) {
                        strBuf.append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\"")
                                .append(inputName).append("\"\r\n\r\n");
                        strBuf.append(inputValue);
                    } else {
                        strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; name=\"")
                                .append(inputName).append("\"\r\n\r\n");
                        strBuf.append(inputValue);
                    }
                    i++;
                }
                out.write(strBuf.toString().getBytes());
            }
            // 读取文件信息，将要上传的文件写入到输出流中。
            File file = new File(localFile);
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(boundary)
                    .append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"file\"; " + "filename=\"")
                    .append(filename).append("\"\r\n");
            strBuf.append("Content-Type: ")
                    .append(contentType)
                    .append("\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据。
            strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.err.println("Send post request exception: " + e);
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}
